package com.sso.shiro;

import com.alibaba.fastjson.JSONObject;
import com.sso.common.ConstantDate;
import com.sso.common.enums.FlagStatus;
import com.sso.common.enums.SysResourceEnum;
import com.sso.entity.SysResource;
import com.sso.manager.SysResourceManager;
import com.tools.util.JSONUtils;
import com.tools.util.StrUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyFormAuthenticationFilter extends FormAuthenticationFilter{
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private SysResourceManager resourceManager;
    @Override
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return isUrlStatus(request,response)&&(isAccessAllowed(request, response, mappedValue) || onAccessDenied(request, response, mappedValue));
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpRequest=(HttpServletRequest)request;
        HttpServletResponse httpResponse=(HttpServletResponse)response;
        String type=httpRequest.getHeader("X-Requested-With");
        if("XMLHttpRequest".equals(type)) {
            if (isLoginRequest(request, response)) {
                if (isLoginSubmission(request, response)) {
                    JSONObject json = new JSONObject();
                    json.put("status", FlagStatus.ERROR.value);
                    json.put("info", "您登陆超时请重新登陆");
                    httpResponse.getWriter().print(json.toJSONString());
                    return false;
                } else {
                    return true;
                }
            } else {
                JSONObject json = new JSONObject();
                json.put("status", FlagStatus.ERROR.value);
                json.put("info", "您没有权限访问");
                httpResponse.getWriter().print(json.toJSONString());
                return false;
            }
        }else{
            if (isLoginRequest(request, response)) {
                if (isLoginSubmission(request, response)) {
                    return executeLogin(request, response);
                } else {
                    return true;
                }
            } else {
                saveRequestAndRedirectToLogin(request, response);
                return false;
            }
        }
    }

    /**
     * 校验文章地址是否正确
     * @param request
     * @return
     */
    protected boolean isUrlStatus(ServletRequest request,ServletResponse response){
        boolean flag=true;
        try {
            HttpServletRequest httpRequest = WebUtils.toHttp(request);
            HttpServletResponse httpResponse = WebUtils.toHttp(response);
            String url = httpRequest.getServletPath();
            SysResource resource = resourceManager.selectByURL(url);
            if(StrUtils.isEmpty(resource.getId())){
                return true;
            }
            String type=httpRequest.getHeader("X-Requested-With");
            String msg =isUrlAccessStatus(httpRequest);
            if(StrUtils.isNotEmpty(msg)){
                if("XMLHttpRequest".equals(type)){
                    JSONUtils.outputJson(FlagStatus.ERROR.value,msg,httpResponse);
                    flag = false;
                }else {
                    if(SysResourceEnum.status.DEL.key.equals(resource.getStatus())){
                        WebUtils.toHttp(response).sendError(HttpServletResponse.SC_NOT_FOUND);
                        flag=false;
                    }else if(SysResourceEnum.status.STOP.key.equals(resource.getStatus())){
                        WebUtils.toHttp(response).sendError(HttpServletResponse.SC_FORBIDDEN);
                        flag=false;
                    }else{

                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 判断URL访问状态
     * @param request
     * @return
     */
    private String isUrlAccessStatus(HttpServletRequest request){
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        String url = httpRequest.getServletPath();
        SysResource resource = resourceManager.selectByURL(url);
        String status="";
        if(StrUtils.isEmpty(resource.getId())){
            return status;
        }
        if(SysResourceEnum.status.DEL.key.equals(resource.getStatus())){
            return "很抱歉，您要访问的地址不存在！";
        }else if(SysResourceEnum.status.STOP.key.equals(resource.getStatus())){
            return "很抱歉，您访问的地址已经暂停访问，如有问题请联系管理人员";
        }else{
            return status;
        }
    }
}
